<?php

namespace backend\controllers;

use common\models\Banner;
use common\service\ConstantService;
use common\service\GlobalUrlService;

class BannerController extends BaseController
{
    public function actionBannerIndex(){
        if($this->isAjax() && $this->isGet()){
            $data = Banner::find()->orderBy(['id'=>SORT_DESC])->asArray()->all();
            foreach ($data as &$val){
                $val['img_url'] = GlobalUrlService::buildCdnUrl($val['img_url']);
            }
            return $this->renderPageJson($data,count($data),ConstantService::$response_tab_success);

        }
        return $this->render('banner-index');
    }

    /**
     * 添加Banner
     * @return string|void
     */
    public function actionBannerAdd(){
        if($this->isAjax() && $this->post()){
            $data = $this->post();
            $data['create_time'] = time();
            $data['update_time'] = time();
            $data['is_del'] = 0;
            $bannerDb = new Banner();
            $bannerDb->setAttributes($data);
            if($bannerDb->save()){
                return $this->renderJson([],"添加成功",ConstantService::$response_success);
            }
            return $this->renderJson([],"添加失败",ConstantService::$response_fail);
        }
        return $this->render('banner-add');
    }

    /**
     * 修改
     * @return string|void
     */
    public function actionBannerUpdate(){
        if($this->isAjax() && $this->post()){
            $data = $this->post();
            $id = $data['id'];
            $BannerData = Banner::findOne(['id'=>$id]);
            $BannerData->oid = $data['oid'];
            $BannerData->img_url = $data['img_url'];
            $BannerData->type = $data['type'];
            $BannerData->show_platform = $data['show_platform'];
            $BannerData->update_time = time();
            if($BannerData->save()){
                return $this->renderJson([],"修改成功",ConstantService::$response_success);
            }
            return $this->renderJson([],"修改失败",ConstantService::$response_fail);
        }
        $id = $this->get('id');
        $list = Banner::find()->where(['id'=>$id])->one();
        return $this->render('banner-update',['data'=>$list]);
    }

    public function actionBannerDel(){
        $id = $this->post('id');
        $data = Banner::findOne(['id'=>$id]);
        if($data['is_del'] == 1){
            $data->is_del = 0;
        } else {
            $data->is_del = 1;
        }
        $data->update_time = time();
        if($data->save()){
            return $this->renderJson([],"修改成功",ConstantService::$response_success);
        }
        return $this->renderJson([],"修改失败",ConstantService::$response_fail);
    }
}